import React, { useState, useEffect } from 'react';
import { FileCheck, RefreshCw, Download, Copy } from 'lucide-react';
import axios from 'axios';
import { toast } from 'react-hot-toast';

const StdPage = () => {
  const [inputText, setInputText] = useState('');
  const [standardizedResults, setStandardizedResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [showResults, setShowResults] = useState(false);

  const [termTypes, setTermTypes] = useState({
    'FINTERM': '金融术语'
  });
  const [embeddingOptions, setEmbeddingOptions] = useState({
    provider: 'huggingface',
    model: 'BAAI/bge-m3',
    dbName: 'finance_terms_bge_m3',
    collectionName: 'financial_concepts'
  });

  const handleStandardize = async () => {
    if (!inputText.trim()) {
      toast.error('请输入需要标准化的金融文本');
      return;
    }

    setLoading(true);
    setShowResults(false);

    try {
      const response = await axios.post('/api/std', {
        text: inputText,
        termTypes: termTypes,
        embeddingOptions: embeddingOptions
      });

      if (response.data.standardized_terms && response.data.standardized_terms.length > 0) {
        setStandardizedResults(response.data.standardized_terms);
        setShowResults(true);
        toast.success('金融术语标准化完成');
      } else {
        toast.info('未识别到需要标准化的金融术语');
        setStandardizedResults([]);
        setShowResults(false);
      }
    } catch (error) {
      console.error('标准化请求失败:', error);
      toast.error('标准化处理失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleCopyResults = () => {
    const resultText = standardizedResults.map(item => {
      return `原始术语: ${item.original_term}\n标准术语: ${item.standardized_results[0]?.concept_name || '未找到标准术语'}\n`;
    }).join('\n');

    navigator.clipboard.writeText(resultText).then(() => {
      toast.success('结果已复制到剪贴板');
    }).catch(err => {
      console.error('复制失败:', err);
      toast.error('复制失败，请手动复制');
    });
  };

  const handleDownloadResults = () => {
    const resultText = standardizedResults.map(item => {
      return `原始术语: ${item.original_term},标准术语: ${item.standardized_results[0]?.concept_name || '未找到标准术语'}`;
    }).join('\n');

    const blob = new Blob([resultText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '金融术语标准化结果.txt';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    toast.success('结果已下载');
  };

  return (
    <div className="max-w-5xl mx-auto">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-4">金融术语标准化</h1>
        <p className="text-gray-600">输入包含金融术语的文本，系统将自动识别并标准化为行业标准表述</p>
      </div>

      <div className="bg-white rounded-lg shadow-md p-6 mb-8">
        <div className="mb-4">
          <label htmlFor="textInput" className="block text-sm font-medium text-gray-700 mb-2">
            输入文本
          </label>
          <textarea
            id="textInput"
            className="input-field"
            rows={4}
            placeholder="请输入需要标准化的金融文本，例如：'该公司的EBITDA同比增长了15%，ROE达到了18%'"
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
          ></textarea>
        </div>



        <div className="mb-6 bg-gray-50 p-4 rounded-lg">
          <h3 className="text-sm font-medium text-gray-700 mb-3">术语类型</h3>
          <div className="flex flex-wrap gap-2">
            {Object.entries(termTypes).map(([key, value]) => (
              <span key={key} className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                {value}
              </span>
            ))}
          </div>
        </div>

        <div className="flex justify-end space-x-3">
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => setInputText('')}
          >
            清空
          </button>
          <button
            type="button"
            className="btn btn-primary"
            onClick={handleStandardize}
            disabled={loading || !inputText.trim()}
          >
            {loading ? (
              <> <RefreshCw className="animate-spin -ml-1 mr-2 h-4 w-4" /> 处理中... </>
            ) : (
              <> <FileCheck className="-ml-1 mr-2 h-4 w-4" /> 开始标准化 </>
            )}
          </button>
        </div>
      </div>

      {showResults && (
        <div className="card fade-in overflow-hidden">
          <div className="bg-gray-50 px-6 py-4 border-b border-gray-200 flex justify-between items-center">
            <h2 className="text-lg font-semibold text-gray-900">标准化结果</h2>
            <div className="flex space-x-2">
              <button
                className="p-2 rounded-md text-gray-600 hover:text-gray-900 hover:bg-gray-100 focus:outline-none"
                onClick={handleCopyResults}
                title="复制结果"
              >
                <Copy className="h-5 w-5" />
              </button>
              <button
                className="p-2 rounded-md text-gray-600 hover:text-gray-900 hover:bg-gray-100 focus:outline-none"
                onClick={handleDownloadResults}
                title="下载结果"
              >
                <Download className="h-5 w-5" />
              </button>
            </div>
          </div>

          <div className="divide-y divide-gray-200">
            {standardizedResults.map((item, index) => (
              <div key={index} className="px-6 py-4 hover:bg-gray-50">
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <span className="text-sm font-medium text-gray-900">原始术语:</span>
                    <span className="ml-2 text-sm text-gray-700 font-semibold">{item.original_term}</span>
                  </div>
                  <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                    {item.entity_group}
                  </span>
                </div>

                <div className="ml-6 mt-2">
                  <span className="text-sm font-medium text-gray-900">推荐标准术语:</span>
                  <div className="mt-1 space-y-2">
                    {item.standardized_results.slice(0, 3).map((result, resIndex) => (
                      <div key={resIndex} className="flex items-center">
                        <span className={`flex h-2 w-2 rounded-full ${resIndex === 0 ? 'bg-green-500' : 'bg-gray-300'} mr-2`}></span>
                        <div>
                          <p className="text-sm text-gray-800">{result.concept_name}</p>
                          <p className="text-xs text-gray-500">匹配度: {(1 - result.distance).toFixed(4)}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default StdPage;